<template>
  <el-scrollbar style="height: 100%" class="opration-container">
    <div class="opration">
      <div class="oprationLeft">
        <!-- <bs-refresh-button-icon @click.native="doRefresh"></bs-refresh-button-icon>
        <el-select class="show-item" size="small" v-model="showItem" :placeholder="$t('显示子元素')" clearable style="width:105px;margin-right:6px;" @change="doChangeItem" @clear="doClearItem(false)">
            <el-option v-for="(item, index) in showItemData" :key="index" :label="$t(item.name)" :value="item.value"></el-option>
        </el-select>
        <bs-set-index-button-icon :show-icon="false" @click.native="doSetIndex" v-has="'SCREEN_TAG_SAVE'"></bs-set-index-button-icon>
    -->
      </div>
      <div class="oprationRight">
        <el-form :inline="true" size="small" :model="queryData">
          <el-form-item>
            <el-button type="primary" size="small" @click="showStateSummary">{{
              '状态汇总'
            }}</el-button>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" size="small" @click="outputXlsxFile">{{
            $t('导出表格')
          }}</el-button>
            <!-- <download-excel
              type="primary"
              class="export-excel-wrapper"
              :fetch="handleExport"
              :fields="excelDataFields"
              :worksheet="worksheet"
              :name="excelFileName"
            >
              <el-button type="primary" size="small">{{
                $t('导出表格')
              }}</el-button>
            </download-excel> -->
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryData.queryType"
              placeholder="全部选项"
              clearabler
              style="width: 100px"
              @clear="doClearQuery"
            >
              <el-option
                v-for="(item, index) in searchItemData"
                :key="index"
                :label="$t(item.name)"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              placeholder="请输入关键词搜索"
              v-model="queryData.queryParam"
              clearable
              style="width: 160px"
            >
              <template slot="prepend"
                ><i class="iconfont icon-sousuo"
              /></template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <bs-search-button-icon
              @click.native="doList"
            ></bs-search-button-icon>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-scrollbar>
</template>
<script>
import ScreenApi from '@/api/screen'
import XLSX from 'xlsx'
export default {
  name: 'DeviceLogCondition',
  data() {
    return {
      columnHeaders: {
        screenData: [
          {
            label: '终端名称',
            prop: 'name',
            minwidth: '100',
          },
          {
            label: 'MAC地址',
            prop: 'macText',
            width: '100',
          },
          {
            label: '版本',
            prop: 'swVersion',
            minwidth: '100',
          },

          {
            label: '车辆编号',
            prop: 'carNo',
            minwidth: '80',
          },
          {
            label: '车牌号码',
            prop: 'carLicense',
            minwidth: '80',
          },
          { label: '线路', prop: 'lineNo', minwidth: '80' },
          {
            label: '所属公司',
            prop: 'busCompany',
            minwidth: '80',
          },
          {
            label: '最后心跳',
            prop: 'lastHeartTime',
            minwidth: '120',
          },
          {
            label: '最后在线',
            prop: 'lastOnlineTime',
            minwidth: '120',
          },
          {
            label: '最后一次正确提交',
            prop: 'lastScreenNormalTime',
            minwidth: '150',
          },
          {
            label: '1号屏/故障说明',
            prop: 'b',
            slot: true,
            minwidth: '120',
          },
          {
            label: '2号屏/故障说明',
            prop: 'c',
            slot: true,
            minwidth: '120',
          },
          {
            label: '3号屏/故障说明',
            prop: 'd',
            slot: true,
            minwidth: '120',
          },
          {
            label: '4号屏/故障说明',
            prop: 'e',
            slot: true,
            minwidth: '120',
          },
          {
            label: '5号屏/故障说明',
            prop: 'f',
            slot: true,
            minwidth: '120',
          },
          { label: '地址码调试', prop: 'screenDebugState', slot: true },
          { label: '是否异常', prop: 'fault', slot: true },
        ],
        screenSummary: [
          { label: '序号', prop: 'sortNum', minwidth: '50', slot: true },
          { label: '1号屏', prop: 'screena', minwidth: '120', slot: true },
          { label: '2号屏', prop: 'screenb', minwidth: '120', slot: true },
          { label: '3号屏', prop: 'screenc', minwidth: '120', slot: true },
          { label: '4号屏', prop: 'screend', minwidth: '120', slot: true },
          { label: '5号屏', prop: 'screene', minwidth: '120', slot: true },
          { label: '统计', prop: 'stateCount', minwidth: '50' },
        ],
      },
      rows: [],
      searchForm: {},
      showItem: '',
      loading:null,
      showItemData: [
        { name: '显示子元素', value: true },
        { name: '隐藏子元素', value: false },
      ],
      searchItemData: [
        { name: '全部选项', value: 0 },
        { name: '终端名称', value: 1 },
        { name: 'MAC地址', value: 2 },
        { name: '车牌号码', value: 3 },
        { name: '车辆编号', value: 4 },
        { name: '线路 ', value: 5 },
        { name: '所属公交公司', value: 6 },
        { name: '故障码', value: 7 },
        { name: '正常/异常', value: 8 },
      ],
      worksheet: this.$t('物理屏监控统计数据'),
      excelFileName: this.$t('物理屏监控统计数据.xls'),
      excelDataFields: {
        终端名称: 'name',
        MAC地址: 'macText',
        版本: 'swVersion',
        车辆编号: 'carNo',
        车牌号码: 'carLicense',
        线路: 'lineNo',
        所属公司: 'busCompany',
        最后心跳: 'lastHeartTime',
        最后在线: 'lastOnlineTime',
        最后一次正确提交: 'lastScreenNormalTime',

        '1号屏/故障说明': {
          field: 'screens',
          //自定义回调函数
          callback: (value) => this.screenFilter(value, 'b'),
        },
        '2号屏/故障说明': {
          field: 'screens',
          //自定义回调函数
          callback: (value) => this.screenFilter(value, 'c'),
        },
        '3号屏/故障说明': {
          field: 'screens',
          //自定义回调函数
          callback: (value) => this.screenFilter(value, 'd'),
        },
        '4号屏/故障说明': {
          field: 'screens',
          //自定义回调函数
          callback: (value) => this.screenFilter(value, 'e'),
        },
        '5号屏/故障说明': {
          field: 'screens',
          //自定义回调函数
          callback: (value) => this.screenFilter(value, 'f'),
        },
        是否异常: {
          field: 'fault',
          //自定义回调函数
          callback: (value) => {
            if (value) {
              return '否'
            } else {
              return '是'
            }
          },
        },
      },
    }
  },
  mounted() {
    this.$nextTick(function () {})
  },
  props: {
    queryData: {
      default: {},
    },
    allSize: {
      default: false,
    },
    totalSize: {
      default: 0,
    },
  },
  methods: {
    screenFilter(value, code) {
      if (value && value.length > 0) {
        const screen = value.find((item) => item.addr == code)
        if (screen) {
          if (screen.message == '没有屏幕状态提交') {
            return 'x/' + screen.message
          } else {
            return screen.code + '/' + screen.message
          }
        } else {
          return 'x/没有屏幕状态提交'
        }
      }
      return 'x/没有屏幕状态提交'
    },
    // 刷新
    doRefresh() {
      this.doList()
      this.$message.success('刷新成功')
    },
    // 显示子元素
    doChangeItem(val) {
      this.queryData.showChild = val
      this.doList()
    },
    doClearItem() {
      this.queryData.showChild = false
    },
    // 查询
    doList() {
      this.queryData.page = 1
      this.$eventBus.$emit('doList', this.queryData)
    },
    // 点击清除下拉选择条件
    doClearQuery() {
      // this.queryData.queryType = 0
      // this.queryData.queryParam = ''
      this.$set(this.queryData, 'queryType', 0)
      this.$set(this.queryData, 'queryParam', '')
    },
    //屏幕统计汇总
    showStateSummary() {
      this.$emit('showSummary')
    },
    //表格导出
    // async handleExport(){
    //   console.log('handleExport')
    //   const res = await ScreenApi.physicalScreenList(this.queryData)
    //   if(res) {
    //     return res.records ? res.records : []
    //   }else{
    //     this.$alert('提示', '终端数据为空')
    //   }
    // },
    async handleExport() {
      if (this.allSize) {
        let params = {
          ...this.queryData,
          allSize: this.allSize,
          total: this.totalSize,
        }
        console.log('handleExport', params)
        const res = await ScreenApi.physicalScreenList(params)
        if (res) {
          return res.records ? res.records : []
        } else {
          this.$alert('提示', '终端数据为空')
        }
      } else {
        // console.log('handleExport',this.rows)
        if (this.rows && this.rows.length > 0) {
          setTimeout(() => {
            this.$emit('resetCheck')
          }, 1000)

          return this.rows
        } else {
          console.log('handleExport', this.rows)
          this.$alert('提示', '请选择需要导出的数据')
        }
      }
    },

    //行选择变化
    selectChange(val) {
      this.rows = val
    },

    async outputXlsxFile() {
      let sheetNames = ['物理屏监控']
      let sheetsList = {
        '物理屏监控': {}
      }
      let tableHeaders =  {
          screenData: [
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
          ],
          screenSummary: [
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
          ],
        }
        this.updateLoading(true)
      let screenData = await this.getScreenMonitorData()
      let summaryData = await this.getScreenSummaryData()
      
      const wb = XLSX.utils.book_new()
      let temp1 = this.transferScreenData(
        screenData,
        this.columnHeaders.screenData
      )
      sheetsList['物理屏监控'] = XLSX.utils.aoa_to_sheet(temp1)
      sheetsList['物理屏监控']['!cols'] = tableHeaders.screenData
      if(this.allSize){
        sheetNames.push('统计汇总')
        sheetsList['统计汇总'] = {}
        let temp2 = this.transferSummary(
          summaryData,
          this.columnHeaders.screenSummary
        )
        sheetsList['统计汇总'] = XLSX.utils.aoa_to_sheet(temp2)
        sheetsList['统计汇总']['!cols'] = tableHeaders.screenSummary
      }
     
      wb['SheetNames'] = sheetNames
      wb['Sheets'] = sheetsList

      XLSX.writeFile(wb, '物理屏监控.xlsx')
      this.updateLoading(false)
    },
 /**
     * 屏幕监控数据
     */
    async getScreenMonitorData(){
      if (this.allSize) {
        let params = {
          ...this.queryData,
          allSize: this.allSize,
          total: this.totalSize,
        }
        console.log('handleExport', params)
        const res = await ScreenApi.physicalScreenList(params)
        if (res) {
          return res.records ? res.records : []
        } else {
          this.$alert('提示', '终端数据为空')
        }
      } else {
        // console.log('handleExport',this.rows)
        if (this.rows && this.rows.length > 0) {
          setTimeout(() => {
            this.$emit('resetCheck')
          }, 1000)
          return this.rows
        } else {
          console.log('handleExport', this.rows)
          this.$alert('提示', '请选择需要导出的数据')
        }
      }
    },
    /**
     * 屏幕汇总统计数据
     */
    async getScreenSummaryData(){
       var params = {}
      if (this.queryData.groupId) {
        params = {
          groupId: this.queryData.groupId,
        }
      } else {
        params = {
          groupId: -2,
        }
      }
      const summary = await ScreenApi.physicalScreenStateSummary(params)
      if (Array.isArray(summary)) {
       return summary
      }
    },
    transferScreenData(data, columnHeader) {
      let content = []
      let headers = []
      columnHeader.map((column) => {
        headers.push(column.label)
      })
      console.log('sheetsList screenData', data,columnHeader)
      content.push(headers)
      data.forEach((item, index) => {
        let arr = []
        columnHeader.map((column) => {
          if (column.slot) {
            console.log(column.prop, '=====================')
            if(column.prop == 'fault'){
              //是否异常处理
              if (item[column.prop]) {
                 arr.push('否')
                } else {
                  arr.push('是')
                }
            } else if(column.prop == 'screenDebugState') {
              if (item[column.prop]) {
                arr.push('已调试')
              } else {
                arr.push('未调试')
              }
            }else{
              let col = this.screenFilter(item.screens, column.prop)
              arr.push(col)
            }
            
          } else {
            arr.push(item[column.prop])
          }
        })
        content.push(arr)
      })
      return content
    },
    transferSummary(data, columnHeader) {
      let content = []
      let headers = []
      columnHeader.map((column) => {
        headers.push(column.label)
      })
      content.push(headers)
      data.forEach((item, index) => {
        let arr = []
        columnHeader.map((column) => {
          if (column.slot) {
            if (column.prop == 'sortNum') {
              arr.push(index + 1)
            } else {
              let col = this.formatSrceen(item[column.prop])
              arr.push(col)
            }
          } else {
            arr.push(item[column.prop])
          }
        })
        content.push(arr)
      })
      return content
    },
    formatSrceen(val) {
      if (val.message == '没有屏幕状态提交') {
        return 'x/' + val.message
      } else {
        return val.code + '/' + val.message
      }
    },
     updateLoading(val){
      if(val){
        if (this.loading === null) {
          this.loading = this.$loading({
            fullscreen: true,
            text: '正在导出物理屏数据',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        }
      }else{
        if (this.loading) {
          this.loading.close()
          this.loading = null
        }
      }
    },
  },

}
</script>